const lowCodeInstance = Symbol("lowCodeInstance");
import clone from "clone";
import { v4 as uuidv4 } from "uuid";
import { tools } from "../page-designer/utils";
import { LowCodeImp, ComponentImp, CellImp } from './type'
export class Component implements ComponentImp {
  private [lowCodeInstance]: LowCodeImp;
  private metaRefresh?: string;
  key!: string;
  type!: string;
  name!: string;
  model!: string[];
  selector!: string;
  group!: string;
  describe!: string;
  nestedChain!: string;
  options!: any;
  style?: any;
  items!: Array<ComponentImp | CellImp>;
  [prop: string]: any
  constructor(options: { [x: string]: any; hasOwnProperty: (arg0: string) => any; }, lowcode: LowCodeImp, newKey?: boolean) {
    for (let name in options) {
      if (options.hasOwnProperty(name)) {
        this[name] = clone(options[name]);
      }
    }
    this[lowCodeInstance] = <LowCodeImp>lowcode
    if (!this.key || newKey) {
      this.key = uuidv4()
    }
    if (!this.selector) {
      this.selector = this.type + '_' + tools.random(5)
    }
    this.modelBing()
  }

  updateMetaRefresh() {
    this.metaRefresh = uuidv4()
  }
  getLowCodeInstance() {
    return this[lowCodeInstance]
  }

  modelBing() {
    if (!this.model) {
      this.model = []
    }
    let list = [...this.model]
    let arr = (list.pop() || '').split('.')
    var end = arr.pop()
    let map: { [key: string]: any } = this[lowCodeInstance].model
    try {
      while (arr.length > 0) {
        let keyName = arr.shift()
        if (keyName) {
          map = map[keyName]
        }
      }

      if (end) {
        (this['options'] as { value: any }).value = map[end]
      }
    } catch (error) {
      throw new Error("数据模型绑定出错")
    }

    Object.defineProperty(this['options'], 'value', {
      get() {
        if (end) {
          return map[end];
        }

      },
      set(value) {
        if (end) {
          map[end] = value;
        }
      },
    });

  }


}



